package com.wenjh.jdmzt.android.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import cn.immob.sdk.ImmobView;
import cn.smartmad.ads.android.SMAdInterstitial;
import cn.smartmad.ads.android.SMAdManager;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.R;
import com.wenjh.jdmzt.android.synctask.BaseTask;
import com.wenjh.jdmzt.android.synctask.Callback;
import com.wenjh.jdmzt.android.synctask.LoadImageTask;
import com.wenjh.jdmzt.android.synctask.LoadImageUtil;
import com.wenjh.jdmzt.android.synctask.ProgessCallback;
import com.wenjh.jdmzt.android.synctask.ThreadPool;
import com.wenjh.jdmzt.android.view.ActionButton;
import com.wenjh.jdmzt.android.view.MProgressDialog;
import com.wenjh.jdmzt.android.view.photoview.PhotoView;
import com.wenjh.jdmzt.service.model.Image;
import com.wenjh.jdmzt.util.FormatUtils;
import com.wenjh.jdmzt.util.IOUtils;
import com.wenjh.jdmzt.util.Log4Android;
import com.wenjh.jdmzt.util.Toaster;

public class ImageBrowserActivity extends BaseActivity {
	public final static String KEY_IMAGES_URLARRAY = "urlarray";
	public final static String KEY_INDEX = "index";
	private ViewPager viewPager;
	List<BrowserImage> imagelist = new ArrayList<BrowserImage>();
	Handler handler = new Handler();
	ViewPagerAdapter adapter = null;
	
	private static ThreadPool localThreadPoll = new ThreadPool(3, 10);
	private static ThreadPool g3NetThreadPoll = new ThreadPool(1, 2);
	private static ThreadPool wifiNetThreadPoll = new ThreadPool(3, 5);
	private ActionButton saveButton = null;
	SMAdInterstitial sMAdInterstitial = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_imagebrowser);
		
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		
		String[] urlArray = getIntent().getStringArrayExtra(KEY_IMAGES_URLARRAY);
		if(urlArray == null || urlArray.length == 0) {
			finish();
			Toaster.show("由于参数异常，图片浏览发生错误");
			return;
		}
		
		for (String string : urlArray) {
			BrowserImage image = new BrowserImage();
			image.image = new Image(string);
			imagelist.add(image);
		}
		
		viewPager.setAdapter(adapter = new ViewPagerAdapter());
		int index = getIntent().getIntExtra(KEY_INDEX, 0);
		if(index < 0) {
			index = 0;
		}
		if(index > imagelist.size()-1) {
			index = imagelist.size()-1;
		}
		viewPager.setCurrentItem(index);
		setTitle("图片浏览("+(index+1)+"/"+imagelist.size()+")");
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				if(arg0 < imagelist.size()) {
					setTitle("图片浏览("+(arg0+1)+"/"+imagelist.size()+")");
					saveButton.setVisibility(View.VISIBLE);
				} else {
					setTitle("推广");
					saveButton.setVisibility(View.GONE);
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
		
		addHeaderButton(saveButton = new ActionButton(getApplicationContext()).setIconResource(R.drawable.ic_topbar_save), new OnClickListener() {
			@Override
			public void onClick(View v) {
				executeAsyncTask(new DownLoadImage(ImageBrowserActivity.this));
			}
		});
		
		// 广告
		SMAdManager.setApplicationId(this,"b94e609cdc9463fd");
		SMAdManager.setAdRefreshInterval(15);
		SMAdManager.setDebuMode(true);
//		sMAdInterstitial = new SMAdInterstitial(this, "90033369",
//				SMAdInterstitial.AD_INTERSTITIAL_MEASURE_AUTO);
//		sMAdInterstitial.requestAd();
		
//		SMAdBannerView smAdBannerView = new SMAdBannerView(this);
//		smAdBannerView = new SMAdBannerView(this, "b94e609cdc9463fd",
//				SMAdBannerView.AUTO_AD_MEASURE);
	}

	private void showBanner() {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				sMAdInterstitial.show();
			}
		}, 1000);
	}
	
	class ViewPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imagelist.size();
		}

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			if(position >= imagelist.size()) {
//				showBanner();
//				return new FrameLayout(getApplicationContext());
//				ImmobView lmView = new ImmobView(ImageBrowserActivity.this, "1891c752b1fd70718bc830b5da1221a4");
//				lmView.display();
//				return lmView;
				
//				SMAdBannerView smAdBannerView = new SMAdBannerView(ImageBrowserActivity.this, "b94e609cdc9463fd",
//						SMAdBannerView.AUTO_AD_MEASURE);
//				return smAdBannerView;
			}
			
			View view = AndroidKit.getLayoutInflater().inflate(R.layout.listitem_browserimage, null);
			PhotoView photoView = (PhotoView) view.findViewById(R.id.imageview);
			BrowserImage browserImage = imagelist.get(position);
			View progressView = view.findViewById(R.id.browswrimage_layout_progressbar);
			
			Bitmap bitmap = LoadImageUtil.getImage(
					LoadImageUtil.getImageIndex(browserImage.image.getImageId(), false));
			if(bitmap != null) {
				photoView.setImageBitmap(bitmap);
				progressView.setVisibility(View.GONE);
			} else {
				if(browserImage.imageCallBack != null && !browserImage.imageCallBack.isFinish) {  // 之前已经开始加载了
					browserImage.imageCallBack.setPhotoView(photoView);
					if(browserImage.progressCallback != null) {
						// 之前就已经开始的图片加载进度，将这个进度显示附加到新的 View 上
						TextView totalView = (TextView) view.findViewById(R.id.browswrimage_tv_progress_totallength);
						TextView percentView = (TextView) view.findViewById(R.id.browswrimage_tv_progress_percent);
						browserImage.progressCallback.percentViewReference = new WeakReference<TextView>(percentView);
						browserImage.progressCallback.totalViewReference = new WeakReference<TextView>(totalView);
						browserImage.progressCallback.reflushProgessView();
						browserImage.imageCallBack.setProgressView(progressView);
						progressView.setVisibility(View.VISIBLE);
					} else {
						progressView.setVisibility(View.GONE);
					}
				} else {
					LoadImageTask imageTask = new LoadImageTask(browserImage.image);
					browserImage.imageCallBack = new ImageCallBack(photoView, handler, browserImage.image.getImageId());
					imageTask.addCallback(browserImage.imageCallBack);
					browserImage.progressCallback = new ImageProgessCallback(handler);
					// 在网上加载图片要实时显示进度
					TextView totalView = (TextView) view.findViewById(R.id.browswrimage_tv_progress_totallength);
					TextView percentView = (TextView) view.findViewById(R.id.browswrimage_tv_progress_percent);
					browserImage.progressCallback.percentViewReference = new WeakReference<TextView>(percentView);
					browserImage.progressCallback.totalViewReference = new WeakReference<TextView>(totalView);
					
					imageTask.setProgessCallback(browserImage.progressCallback);
					browserImage.imageCallBack.setProgressView(progressView);
					progressView.setVisibility(View.VISIBLE);

					ThreadPool threadPool = null;
					if(imageTask.isLocalExists()) {
						threadPool = localThreadPoll;
					} else {
						
						if(AndroidKit.isWifi()) {
							threadPool = wifiNetThreadPoll;
						} else {
							threadPool = g3NetThreadPoll;
						}
					}
					
					threadPool.execute(imageTask);
				}
			}

			container.addView(view);

			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}
	
	@Override
	protected void initEvents() {
	}

	@Override
	protected void initViews() {
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		g3NetThreadPoll.getQueue().clear();
		localThreadPoll.getQueue().clear();
		wifiNetThreadPoll.getQueue().clear();
	}
	
	private static class BrowserImage {
		Image image = null;
		ImageProgessCallback progressCallback = null;
		ImageCallBack imageCallBack = null;
	}
	
	private static class ImageCallBack implements Callback<Bitmap> {
		private WeakReference<PhotoView> photoViewReference = null;
		private WeakReference<View> progressViewReference = null;
		private Handler handler = null;
		private String imageid = null;
		boolean isFinish = false;
		
		public ImageCallBack(PhotoView photoView, Handler handler, String imageid) {
			this.photoViewReference = new WeakReference<PhotoView>(photoView);
			this.handler = handler;
			this.imageid = imageid;
		}
		
		public void setPhotoView(PhotoView photoView) {
			this.photoViewReference = new WeakReference<PhotoView>(photoView);
		}
		
		public void setProgressView(View progressView) {
			this.progressViewReference = new WeakReference<View>(progressView);
		}
		
		@Override
		public void afterRun(final Bitmap bitmap) {
			isFinish = true;
			
			if(bitmap != null) {
				LoadImageUtil.putImage(LoadImageUtil.getImageIndex(imageid, false), bitmap);
			}
			
			handler.post(new Runnable() {
				@Override
				public void run() {
					if(bitmap != null) {
						PhotoView photoView = null;
						if(photoViewReference != null) {
							photoView = photoViewReference.get();
						}
						if(photoView != null) {
							photoView.setImageBitmap(bitmap);
						}
					}
					
					// 下载完成后取消显示进度
					View progessView = null;
					if(progressViewReference != null) {
						progessView = progressViewReference.get();
					}
					if(progessView != null) {
						progessView.setVisibility(View.GONE);
					}
				}
					
			});
		}
	}; 
	
	private static class ImageProgessCallback implements ProgessCallback {
		private long currentPosition = 0;
		private long totalLength = 0;
		private Handler handler = null;
		private WeakReference<TextView> totalViewReference = null;
		private WeakReference<TextView> percentViewReference = null;
		private Log4Android log = new Log4Android(this);
		public ImageProgessCallback(Handler handler) {
			this.handler = handler;
		}
		
		public void reflushProgessView() {
			TextView totalView = null;
			TextView percentView = null;
			
			if(totalViewReference != null) {
				totalView = totalViewReference.get();
			}
			
			if(percentViewReference != null) {
				percentView = percentViewReference.get();
			}
			
			String percent = "";
			if(totalLength == -2) {
				percent = "加载图片缓存";
				return;
			} else if(totalLength < 0) {
				percent = "下载失败";
				return;
			} else if(totalLength == 0) {
				percent = "连接中...";
			} else {
				percent = (currentPosition * 100 / totalLength)+"%";
			}
			
			if(percentView != null) {
				percentView.setText(percent);
			}
			
			if(totalView != null) {
				if(totalLength > 0) {
					totalView.setVisibility(View.VISIBLE);
					totalView.setText((currentPosition/1024) +"kb/"+ (totalLength/1024+"kb"));
				} else {
					totalView.setVisibility(View.GONE);
				}
			}
		}
 		
		@Override
		public void onProgessChanged(long currentPosition, long totalLength) {
			this.currentPosition = currentPosition;
			this.totalLength = totalLength;
			handler.post(new Runnable() {
				@Override
				public void run() {
					reflushProgessView();
				}
			});
		}
	}
	
	
	private class DownLoadImage extends BaseTask<Object, Object, Object> {
		Image image = null;
		public DownLoadImage(Context context) {
			super(context);
			this.image = imagelist.get(viewPager.getCurrentItem()).image;
		}
		
		@Override
		protected void onPreTask() {
			showDialog(new MProgressDialog(ImageBrowserActivity.this, "正在保存图片..."));
		}

		@SuppressLint("NewApi")
		@Override
		protected Object executeTask(Object... params) throws Exception {
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  //存储卡不可用
				Toaster.showInvalidate("图片保存不可用，因为存储卡不可用");
				cancel(true);
			} else {
				File dir = new File(Environment.getExternalStorageDirectory(), "DCIM/美人眼");
				if(!dir.exists()) {
					dir.mkdirs();
				}
				
				File targetFile = new File(dir, image.getImageId()+".jpg");
				if(targetFile.exists() && targetFile.length() > 0) {
					Toaster.showInvalidate("该图已经保存在您的存储卡:DCIM/美人眼/"+targetFile.getName(), Toaster.LENGTH_LONG);
				} else {
					dir = new File(AndroidKit.getApp().getExternalCacheDir(), image.getImageId().substring(0, 1));
					File cacheFile = new File(dir, image.getImageId());
					if(!cacheFile.exists() || cacheFile.length() <= 0) {
						Toaster.showInvalidate("请等待图片下载成功");
					} else {
						InputStream is = null;
						OutputStream os = null;
						try {
							is = new FileInputStream(cacheFile);
							os = new FileOutputStream(targetFile);
							int len = -1;
							byte[] data = new byte[1024];
							while((len = is.read(data)) != -1) {
								os.write(data, 0, len);
							}
							putBitmapIntoGalleryAndGetUri(getApplicationContext(), targetFile);
							Toaster.showInvalidate("图已成功保存在您的存储卡:DCIM/美人眼/"+targetFile.getName(), Toaster.LENGTH_LONG);
						} finally {
							IOUtils.closeQuietly(is);
							IOUtils.closeQuietly(os);
						}
					}
				}
			}
			
			return null;
		}
		
		@Override
		protected void onTaskError(Exception e) {
			toast("图片保存失败");
		}
		
		@Override
		protected void onTaskFinish() {
			closeDialog();
		}
		
		private Uri putBitmapIntoGalleryAndGetUri(Context c, File imageFile) {
	    	 if (imageFile.exists() && imageFile.isFile()) {
	             try {
	            	 ContentValues values = new ContentValues();  
	            	 values.put(Images.Media.MIME_TYPE, "image/jpeg");  
	            	 values.put(Images.Media.DATA, imageFile.getAbsolutePath());  
	            	 values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
	            	 values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
	            	 
	            	 return c.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);  
	             } catch (Exception e) {
	                 e.printStackTrace();
	             }   
	         }
	        
	        return null;
	    }
	}
}
